﻿using System;
using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;

namespace Manager{

	public class ResourceManager:BaseManager
	{
        private DownLoadRemoteFileManager loadRemoteManager;

        private AssetBundleManager assetBundleManager;

        private Action downLoadRemoteFileCallback;

		protected override void Initialization ()
		{
            loadRemoteManager = new DownLoadRemoteFileManager();
            assetBundleManager = new AssetBundleManager();
		}

        protected override void OnUpdate()
        {
        }


        ///====================================游戏初始化接口=======================================

		/// <summary>
		/// 检测资源更新
		/// </summary>
		public void CheckResource(Action completeCallBack){
            downLoadRemoteFileCallback = completeCallBack;
			//if (GameManager.instance.networkManager.Wifi) {
				//检测资源更新时 区分 是否是覆盖或首次安装，清掉应用程序数据存贮目录
				FileTool.ClearDirectory(Application.persistentDataPath);
				//该streamingassets中的所有文件拷贝到数据目录
				FileTool.CopyDirectory (Application.streamingAssetsPath,Application.persistentDataPath);
				//开始更新资源
				StartCoroutine(resourceUpdate());
			//}
		}

        /// <summary>
        /// 更新游戏文件
        /// </summary>
        /// <returns></returns>
		IEnumerator resourceUpdate(){

			WWW www = new WWW(AppConst.ConfigPath);
			yield return www;
			if (www.error != null)
			{
				resourceUpdateError ();
                yield break;
			}
            Debug.LogError("加载成功:" + AppConst.ConfigPath);

            //获得文件信息
            List<string> downLoadList = new List<string>();

			string content = FileTool.ReadFile (www.bytes);
			string[] fileList = content.Split ('\n');
			for (int i = 0; i < fileList.Length; i++) {
                string[] infoArray = fileList[i].Split('|');
                if (infoArray.Length == 2)
                {
                    string localPath = Application.persistentDataPath + "/" + infoArray[0];
                    localPath = PathTool.FormationPath(localPath);
                    if (File.Exists(localPath))
                    {
                        string localMd5 = FileTool.GetMD5HashFromFile(localPath);
                        string remoteMd5 = infoArray[1];
                        if (!localMd5.Equals(remoteMd5))
                        {
                            downLoadList.Add(infoArray[0]);
                        }
                    }
                    else
                    {
                        downLoadList.Add(infoArray[0]);
                    }
                }
			}

            if (downLoadList.Count > 0)
            {
                GameManager.instance.windowManager.ShowLoadingUI("正在进行首次加载资源，本次加载有可能稍慢请您耐心等待!", 0);
                loadRemoteManager.LoadRemoteFile(downLoadList, LoadRemoteFileProgress, LoadRemoteFileComplete);
            }
		}

        private void LoadRemoteFileProgress(float progress)
        {
            GameManager.instance.windowManager.ShowLoadingUI("正在进行首次加载资源，本次加载有可能稍慢请您耐心等待!",progress);
        }

        //更新文件完成
        private void LoadRemoteFileComplete()
        {
            if (downLoadRemoteFileCallback != null)
            {
                downLoadRemoteFileCallback();
                downLoadRemoteFileCallback = null;
            }
            loadRemoteManager.Clear();

            List<string> firstAb = new List<string>();
            firstAb.Add("SceneGlobalDependencies");


            GameManager.instance.resourceManager.LoadAssetBundle(firstAb,
               (float progress) =>
               {
                   GameManager.instance.windowManager.ShowLoadingUI("正在加载游戏主要的AB!", progress);
               },
               () =>
               {
                   GameManager.instance.windowManager.HideLoadingUI();
                   GameContext.dispatcher.Dispatch(new NotifyEvent(NotifyEvent.Type.LoadRemoteFileComplete));
               }
           );
           
        }

        /// <summary>
        /// 更新失败
        /// </summary>
		private void resourceUpdateError(){
			Debug.LogError ("更新资源失败!");
		}

        //=======================================AssetBundle接口===============================

        public void LoadAssetBundle(List<string> bundleList,Action<float> progress = null,Action complete = null)
        {
            assetBundleManager.LoadAssetBundle(bundleList, BundleLoadLevel.height, progress, complete);
        }

        public void LoadAssetBundle(string bundlePath, Action<float> progress = null, Action complete = null)
        {
            List<string> bundleList = new List<string>();
            bundleList.Add(bundlePath);
            LoadAssetBundle(bundleList,progress,complete);
        }

        public AssetBundle GetAssetBundle(string assetBundlePath)
        {
            return assetBundleManager.GetAssetBundle(assetBundlePath);
        }

        public void RemoveAssetBundle(string assetBundlePath, bool unloadAllloadedObjects)
        {
            assetBundleManager.RemoveAssetBundle(assetBundlePath, unloadAllloadedObjects);
        }

        public void RemoveAssetBundle(List<string> assetBundlePathList, bool unloadAllloadedObjects)
        {
            assetBundleManager.RemoveAssetBundle(assetBundlePathList, unloadAllloadedObjects);
        }

	}
}
